import {
  Injectable,
  NotFoundException,
  BadRequestException,
  InternalServerErrorException,
} from '@nestjs/common';
import { PrismaService } from '../../common/prisma/prisma.service';
import { CreateQuestionDto } from './dto/create-question.dto';
import { Prisma } from '@prisma/client';

@Injectable()
export class QuestionBankService {
  constructor(private prisma: PrismaService) {}

  async create(createQuestionDto: CreateQuestionDto) {
    try {
      const existingQuestion = await this.prisma.question_bank.findFirst({
        where: {
          question_desc: createQuestionDto.question_desc,
          is_deleted: 0,
        },
      });

      if (existingQuestion) {
        throw new BadRequestException(`题目内容已存在`);
      }

      // 构建创建数据，只包含数据库中存在的字段
      const createData: Prisma.question_bankCreateInput = {
        question_desc: createQuestionDto.question_desc,
        option_1: createQuestionDto.option_1 ?? '',
        option_2: createQuestionDto.option_2 ?? '',
        option_3: createQuestionDto.option_3 ?? '',
        option_4: createQuestionDto.option_4 ?? '',
        option_5: createQuestionDto.option_5 ?? '',
        option_6: createQuestionDto.option_6 ?? '',
        source: createQuestionDto.source ?? 0,
        grade: createQuestionDto.grade ?? 0,
        correct_option: createQuestionDto.correct_option ?? 0,
        remark: createQuestionDto.remark ?? '',
        knowledge_point_id: createQuestionDto.knowledge_point_id ?? 0,
        model_answer1: createQuestionDto.model_answer1 ?? 0,
        model_answer2: createQuestionDto.model_answer2 ?? 0,
        model_answer3: createQuestionDto.model_answer3 ?? 0,
        model_answer4: createQuestionDto.model_answer4 ?? 0,
        model_answer5: createQuestionDto.model_answer5 ?? 0,
        model_knowledge_point1: createQuestionDto.model_knowledge_point1 ?? '',
        model_knowledge_point2: createQuestionDto.model_knowledge_point2 ?? '',
        model_knowledge_point3: createQuestionDto.model_knowledge_point3 ?? '',
        model_knowledge_point4: createQuestionDto.model_knowledge_point4 ?? '',
        model_knowledge_point5: createQuestionDto.model_knowledge_point5 ?? '',
        model_answer_explanation1:
          createQuestionDto.model_answer_explanation1 ?? '',
        model_answer_explanation2:
          createQuestionDto.model_answer_explanation2 ?? '',
        model_answer_explanation3:
          createQuestionDto.model_answer_explanation3 ?? '',
        model_answer_explanation4:
          createQuestionDto.model_answer_explanation4 ?? '',
        model_answer_explanation5:
          createQuestionDto.model_answer_explanation5 ?? '',
        max_matched_num: createQuestionDto.max_matched_num ?? 0,
        max_matched_answer: createQuestionDto.max_matched_answer ?? 0,
        knowledge_point_code: createQuestionDto.knowledge_point_code ?? '',
        knowledge_point_label: createQuestionDto.knowledge_point_label ?? '',
        create_time: new Date(),
        update_time: new Date(),
        is_deleted: 0,
      };

      const result = await this.prisma.question_bank.create({
        data: createData,
      });

      return {
        question_id: result.question_id,
        ...result,
      };
    } catch (error) {
      console.error('创建题目时发生错误:', error);
      if (error instanceof BadRequestException) {
        throw error;
      }
      if (error instanceof Prisma.PrismaClientKnownRequestError) {
        if (error.code === 'P2002') {
          throw new BadRequestException('题目内容重复');
        }
      }
      throw new InternalServerErrorException('创建题目失败');
    }
  }

  async findAll(query: {
    page?: number;
    size?: number;
    keyword?: string;
    source?: number;
    grade?: number;
    subject_id?: number;
    chapter_id?: number;
    section_id?: number;
    knowledge_point_id?: number;
    difficulty?: number;
    status?: number;
  }) {
    try {
      const { page = 1, size = 10 } = query;
      if (page < 1 || size < 1) {
        throw new BadRequestException('页码和每页数量必须大于0');
      }

      const skip = (page - 1) * size;

      const where = {
        ...(query.keyword && {
          OR: [
            { question_desc: { contains: query.keyword } },
            { remark: { contains: query.keyword } },
          ],
        }),
        ...(query.source !== undefined && { source: query.source }),
        ...(query.grade !== undefined && { grade: query.grade }),
        ...(query.subject_id !== undefined && { subject_id: query.subject_id }),
        ...(query.chapter_id !== undefined && { chapter_id: query.chapter_id }),
        ...(query.section_id !== undefined && { section_id: query.section_id }),
        ...(query.knowledge_point_id !== undefined && {
          knowledge_point_id: query.knowledge_point_id,
        }),
        ...(query.difficulty !== undefined && { difficulty: query.difficulty }),
        ...(query.status !== undefined && { status: query.status }),
        is_deleted: 0,
      };

      const [items, total] = await Promise.all([
        this.prisma.question_bank.findMany({
          where,
          skip,
          take: size,
          orderBy: { create_time: 'desc' },
        }),
        this.prisma.question_bank.count({ where }),
      ]);

      return {
        items,
        total,
        page,
        size,
        totalPages: Math.ceil(total / size),
      };
    } catch (error) {
      console.error('获取题目列表失败:', error);
      throw new InternalServerErrorException('获取题目列表失败');
    }
  }

  async findOne(id: number) {
    try {
      const question = await this.prisma.question_bank.findFirst({
        where: {
          question_id: id,
          is_deleted: 0,
        },
      });

      if (!question) {
        throw new NotFoundException(`题目 ${id} 不存在`);
      }

      return question;
    } catch (error) {
      if (error instanceof NotFoundException) {
        throw error;
      }
      console.error('获取题目详情失败:', error);
      throw new InternalServerErrorException('获取题目详情失败');
    }
  }

  async update(id: number, updateQuestionDto: Partial<CreateQuestionDto>) {
    try {
      await this.findOne(id);

      if (updateQuestionDto.question_desc) {
        const existingQuestion = await this.prisma.question_bank.findFirst({
          where: {
            question_desc: updateQuestionDto.question_desc,
            question_id: { not: id },
            is_deleted: 0,
          },
        });

        if (existingQuestion) {
          throw new BadRequestException(`题目内容已存在`);
        }
      }

      const updateData: Prisma.question_bankUpdateInput = {
        ...(updateQuestionDto.question_desc && {
          question_desc: updateQuestionDto.question_desc,
        }),
        ...(updateQuestionDto.option_1 !== undefined && {
          option_1: updateQuestionDto.option_1,
        }),
        ...(updateQuestionDto.option_2 !== undefined && {
          option_2: updateQuestionDto.option_2,
        }),
        ...(updateQuestionDto.option_3 !== undefined && {
          option_3: updateQuestionDto.option_3,
        }),
        ...(updateQuestionDto.option_4 !== undefined && {
          option_4: updateQuestionDto.option_4,
        }),
        ...(updateQuestionDto.source !== undefined && {
          source: updateQuestionDto.source,
        }),
        ...(updateQuestionDto.grade !== undefined && {
          grade: updateQuestionDto.grade,
        }),
        ...(updateQuestionDto.knowledge_point_code !== undefined && {
          knowledge_point_code: updateQuestionDto.knowledge_point_code,
        }),
        ...(updateQuestionDto.knowledge_point_label !== undefined && {
          knowledge_point_label: updateQuestionDto.knowledge_point_label,
        }),
        ...(updateQuestionDto.knowledge_point_id !== undefined && {
          knowledge_point_id: updateQuestionDto.knowledge_point_id,
        }),
        ...(updateQuestionDto.subject_id !== undefined && {
          subject_id: updateQuestionDto.subject_id,
        }),
        ...(updateQuestionDto.chapter_id !== undefined && {
          chapter_id: updateQuestionDto.chapter_id,
        }),
        ...(updateQuestionDto.section_id !== undefined && {
          section_id: updateQuestionDto.section_id,
        }),
        ...(updateQuestionDto.answer_type !== undefined && {
          answer_type: updateQuestionDto.answer_type,
        }),
        update_time: new Date(),
      };

      const result = await this.prisma.question_bank.update({
        where: { question_id: id },
        data: updateData,
      });

      return result;
    } catch (error) {
      if (
        error instanceof BadRequestException ||
        error instanceof NotFoundException
      ) {
        throw error;
      }
      console.error('更新题目失败:', error);
      throw new InternalServerErrorException('更新题目失败');
    }
  }

  async remove(id: number) {
    try {
      await this.findOne(id);

      const result = await this.prisma.question_bank.update({
        where: { question_id: id },
        data: {
          is_deleted: 1,
          update_time: new Date(),
        },
      });

      return {
        message: '删除成功',
        question_id: result.question_id,
      };
    } catch (error) {
      if (error instanceof NotFoundException) {
        throw error;
      }
      console.error('删除题目失败:', error);
      throw new InternalServerErrorException('删除题目失败');
    }
  }
}
